<template>
  <div class="overdue-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>逾期管理</h3>
          <div class="header-actions">
            <el-tooltip content="双击行可查看催收记录" placement="top">
              <el-icon class="info-icon"><InfoFilled /></el-icon>
            </el-tooltip>
            <el-button type="warning" @click="handleBatchRemind">批量提醒</el-button>
            <el-button type="success" @click="handleExport">导出</el-button>
          </div>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="贷款编号">
          <el-input v-model="searchForm.loanNo" placeholder="请输入贷款编号" clearable></el-input>
        </el-form-item>
        <el-form-item label="客户姓名">
          <el-input v-model="searchForm.customerName" placeholder="请输入客户姓名" clearable></el-input>
        </el-form-item>
        <el-form-item label="逾期天数">
          <el-select v-model="searchForm.overdueDays" placeholder="请选择逾期天数" clearable style="width: 180px;">
            <el-option label="1-30天" value="1-30"></el-option>
            <el-option label="31-60天" value="31-60"></el-option>
            <el-option label="61-90天" value="61-90"></el-option>
            <el-option label="90天以上" value="90+"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="处理状态">
          <el-select v-model="searchForm.status" placeholder="请选择处理状态" clearable style="width: 180px;">
            <el-option label="未处理" value="pending"></el-option>
            <el-option label="已提醒" value="reminded"></el-option>
            <el-option label="已催收" value="collected"></el-option>
            <el-option label="已结清" value="settled"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table 
        :data="tableData" 
        border 
        style="width: 100%" 
        v-loading="loading"
        @selection-change="handleSelectionChange"
        @row-dblclick="handleRowDblClick"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="contractNo" label="合同编号" width="120"></el-table-column>
        <el-table-column prop="loanNo" label="贷款编号" width="120"></el-table-column>
        <el-table-column prop="customerName" label="客户姓名" width="100"></el-table-column>
        <el-table-column prop="phone" label="联系电话" width="120"></el-table-column>
        <el-table-column prop="period" label="逾期期数" width="80"></el-table-column>
        <el-table-column prop="dueDate" label="应还日期" width="100"></el-table-column>
        <el-table-column prop="dueAmount" label="应还金额" width="100">
          <template #default="scope">
            {{ formatMoney(scope.row.dueAmount) }}
          </template>
        </el-table-column>
        <el-table-column prop="overdueDays" label="逾期天数" width="100">
          <template #default="scope">
            <el-tag :type="getOverdueType(scope.row.overdueDays)">{{ scope.row.overdueDays }}天</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="penalty" label="罚息" width="100">
          <template #default="scope">
            {{ formatMoney(scope.row.penalty) }}
          </template>
        </el-table-column>
        <el-table-column prop="totalAmount" label="应还总额" width="100">
          <template #default="scope">
            {{ formatMoney(scope.row.totalAmount) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="处理状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remindCount" label="提醒次数" width="80"></el-table-column>
        <el-table-column prop="calcDate" label="计算日期" width="100"></el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="scope">
            <el-button link type="primary" @click="handleRemind(scope.row)">提醒</el-button>
            <el-button link type="primary" @click="handleCollect(scope.row)">催收</el-button>
            <el-button link type="primary" @click="handleRepay(scope.row)">还款</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 提醒对话框 -->
    <el-dialog v-model="remindDialogVisible" title="发送还款提醒" width="500px">
      <el-form :model="remindForm" label-width="100px">
        <el-form-item label="贷款编号">
          <el-input v-model="remindForm.loanNo" disabled></el-input>
        </el-form-item>
        <el-form-item label="客户姓名">
          <el-input v-model="remindForm.customerName" disabled></el-input>
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="remindForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="提醒方式" required>
          <el-select v-model="remindForm.method" placeholder="请选择提醒方式" style="width: 100%">
            <el-option label="短信" value="sms"></el-option>
            <el-option label="电话" value="phone"></el-option>
            <el-option label="邮件" value="email"></el-option>
            <el-option label="微信" value="wechat"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="提醒内容" required>
          <el-input v-model="remindForm.content" type="textarea" rows="4"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="remindDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitRemind">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 催收对话框 -->
    <el-dialog v-model="collectDialogVisible" title="催收登记" width="500px">
      <el-form :model="collectForm" label-width="100px">
        <el-form-item label="贷款编号">
          <el-input v-model="collectForm.loanNo" disabled></el-input>
        </el-form-item>
        <el-form-item label="客户姓名">
          <el-input v-model="collectForm.customerName" disabled></el-input>
        </el-form-item>
        <el-form-item label="催收方式" required>
          <el-select v-model="collectForm.method" placeholder="请选择催收方式" style="width: 100%">
            <el-option label="电话催收" value="phone"></el-option>
            <el-option label="上门催收" value="visit"></el-option>
            <el-option label="法律催收" value="legal"></el-option>
            <el-option label="委外催收" value="outsource"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="催收人员" required>
          <el-input v-model="collectForm.collector"></el-input>
        </el-form-item>
        <el-form-item label="催收时间" required>
          <el-date-picker v-model="collectForm.collectTime" type="datetime" placeholder="选择催收时间" style="width: 100%"></el-date-picker>
        </el-form-item>
        <el-form-item label="催收结果" required>
          <el-select v-model="collectForm.result" placeholder="请选择催收结果" style="width: 100%">
            <el-option label="承诺还款" value="promise"></el-option>
            <el-option label="拒绝还款" value="refuse"></el-option>
            <el-option label="无法联系" value="unreachable"></el-option>
            <el-option label="部分还款" value="partial"></el-option>
            <el-option label="全部还款" value="full"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="collectForm.remark" type="textarea" rows="3"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="collectDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitCollect">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 还款对话框 -->
    <el-dialog v-model="repayDialogVisible" title="逾期还款" width="500px">
      <el-form :model="repayForm" label-width="120px">
        <el-form-item label="贷款编号">
          <el-input v-model="repayForm.loanNo" disabled></el-input>
        </el-form-item>
        <el-form-item label="客户姓名">
          <el-input v-model="repayForm.customerName" disabled></el-input>
        </el-form-item>
        <el-form-item label="应还金额">
          <el-input v-model="repayForm.dueAmount" disabled></el-input>
        </el-form-item>
        <el-form-item label="罚息">
          <el-input v-model="repayForm.penalty" disabled></el-input>
        </el-form-item>
        <el-form-item label="应还总额">
          <el-input v-model="repayForm.totalAmount" disabled></el-input>
        </el-form-item>
        <el-form-item label="实际还款日期" required>
          <el-date-picker v-model="repayForm.payDate" type="date" placeholder="选择还款日期" style="width: 100%"></el-date-picker>
        </el-form-item>
        <el-form-item label="实际还款金额" required>
          <el-input-number v-model="repayForm.payAmount" :precision="2" :min="0" style="width: 100%"></el-input-number>
        </el-form-item>
        <el-form-item label="还款方式" required>
          <el-select v-model="repayForm.payMethod" placeholder="请选择还款方式" style="width: 100%">
            <el-option label="银行转账" value="1"></el-option>
            <el-option label="现金" value="2"></el-option>
            <el-option label="支付宝" value="3"></el-option>
            <el-option label="微信支付" value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="repayForm.remark" type="textarea" rows="3"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="repayDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitRepay">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 催收记录对话框 -->
    <el-dialog v-model="recordDialogVisible" title="催收记录" width="800px">
      <el-table :data="collectRecords" border style="width: 100%">
        <el-table-column prop="method" label="催收方式" width="120">
          <template #default="scope">
            {{ getCollectMethodText(scope.row.method) }}
          </template>
        </el-table-column>
        <el-table-column prop="collector" label="催收人员" width="120"></el-table-column>
        <el-table-column prop="collectTime" label="催收时间" width="180"></el-table-column>
        <el-table-column prop="result" label="催收结果" width="150"></el-table-column>
        <el-table-column prop="nextCollectTime" label="下次催收时间" width="180"></el-table-column>
        <el-table-column prop="remark" label="备注"></el-table-column>
      </el-table>
    </el-dialog>

    <!-- 批量提醒对话框 -->
    <el-dialog v-model="batchRemindDialogVisible" title="批量发送还款提醒" width="500px">
      <el-form :model="batchRemindForm" label-width="100px">
        <el-form-item label="已选择" prop="selectedCount">
          <el-input v-model="batchRemindForm.overdueIds.length" disabled>
            <template #append>条记录</template>
          </el-input>
        </el-form-item>
        <el-form-item label="提醒方式" required>
          <el-select v-model="batchRemindForm.method" placeholder="请选择提醒方式" style="width: 100%">
            <el-option label="短信" value="sms"></el-option>
            <el-option label="电话" value="phone"></el-option>
            <el-option label="邮件" value="email"></el-option>
            <el-option label="微信" value="wechat"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="提醒内容" required>
          <el-input v-model="batchRemindForm.content" type="textarea" rows="4"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="batchRemindDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitBatchRemind">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { overdueApi, repaymentRecordApi } from '@/api/repayment'
import { InfoFilled } from '@element-plus/icons-vue'

// 表格数据
const loading = ref(false)
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const selectedRows = ref([])

// 搜索表单
const searchForm = reactive({
  loanNo: '',
  customerName: '',
  overdueDays: '',
  status: ''
})

// 提醒对话框
const remindDialogVisible = ref(false)
const remindForm = reactive({
  overdueId: '',
  loanNo: '',
  customerName: '',
  phone: '',
  method: 'sms',
  content: ''
})

// 批量提醒对话框
const batchRemindDialogVisible = ref(false)
const batchRemindForm = reactive({
  overdueIds: [],
  method: 'sms',
  content: ''
})

// 催收对话框
const collectDialogVisible = ref(false)
const collectForm = reactive({
  overdueId: '',
  loanNo: '',
  customerName: '',
  method: '',
  collector: '',
  collectTime: new Date(),
  result: '',
  nextCollectTime: '',
  remark: ''
})

// 还款对话框
const repayDialogVisible = ref(false)
const repayForm = reactive({
  overdueId: '',
  loanNo: '',
  customerName: '',
  dueDate: '',
  dueAmount: '',
  overdueDays: '',
  penalty: '',
  totalAmount: '',
  payDate: new Date(),
  payAmount: '',
  principal: '',
  interest: '',
  payMethod: '1',
  transactionNo: '',
  remark: ''
})

// 催收记录对话框
const recordDialogVisible = ref(false)
const collectRecords = ref([])

// 初始化
onMounted(() => {
  getTableData()
})

// 获取表格数据
const getTableData = () => {
  loading.value = true
  
  const params = {
    pageNum: currentPage.value,
    pageSize: pageSize.value,
    loanNo: searchForm.loanNo,
    customerName: searchForm.customerName,
    overdueDays: searchForm.overdueDays,
    status: searchForm.status
  }
  
  overdueApi.getList(params).then(res => {
    tableData.value = res.data.records
    total.value = res.data.total
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getTableData()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  handleSearch()
}

// 选择行变化
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}

// 发送提醒
const handleRemind = (row) => {
  remindForm.overdueId = row.overdueId
  remindForm.loanNo = row.loanNo
  remindForm.customerName = row.customerName
  remindForm.phone = row.phone
  remindForm.method = 'sms'
  remindForm.content = `尊敬的${row.customerName}客户，您的贷款${row.loanNo}已逾期${row.overdueDays}天，应还金额${row.totalAmount}元，请尽快还款。`
  
  remindDialogVisible.value = true
}

// 提交提醒
const submitRemind = () => {
  if (!remindForm.method || !remindForm.content) {
    ElMessage.warning('请填写完整的提醒信息')
    return
  }
  
  loading.value = true
  
  const data = {
    overdueId: remindForm.overdueId,
    phone: remindForm.phone,
    method: remindForm.method,
    content: remindForm.content
  }
  
  overdueApi.sendRemind(data).then(res => {
    ElMessage.success('发送提醒成功')
    remindDialogVisible.value = false
    getTableData()
  }).catch(() => {
    loading.value = false
  })
}

// 批量提醒
const handleBatchRemind = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择需要发送提醒的记录')
    return
  }
  
  batchRemindForm.overdueIds = selectedRows.value.map(row => row.overdueId)
  batchRemindForm.method = 'sms'
  batchRemindForm.content = '尊敬的客户，您的贷款已逾期，请尽快还款。'
  
  batchRemindDialogVisible.value = true
}

// 提交批量提醒
const submitBatchRemind = () => {
  if (!batchRemindForm.method || !batchRemindForm.content) {
    ElMessage.warning('请填写完整的提醒信息')
    return
  }
  
  loading.value = true
  
  const data = {
    overdueIds: batchRemindForm.overdueIds,
    method: batchRemindForm.method,
    content: batchRemindForm.content
  }
  
  overdueApi.batchRemind(data).then(res => {
    ElMessage.success(`成功发送${res.data.successCount}条提醒，失败${res.data.failCount}条`)
    batchRemindDialogVisible.value = false
    getTableData()
  }).catch(() => {
    loading.value = false
  })
}

// 催收登记
const handleCollect = (row) => {
  collectForm.overdueId = row.overdueId
  collectForm.loanNo = row.loanNo
  collectForm.customerName = row.customerName
  collectForm.method = 'phone'
  collectForm.collector = ''
  collectForm.collectTime = new Date()
  collectForm.result = ''
  collectForm.nextCollectTime = ''
  collectForm.remark = ''
  
  collectDialogVisible.value = true
}

// 提交催收登记
const submitCollect = () => {
  if (!collectForm.method || !collectForm.collector || !collectForm.collectTime || !collectForm.result) {
    ElMessage.warning('请填写完整的催收信息')
    return
  }
  
  loading.value = true
  
  const data = {
    overdueId: collectForm.overdueId,
    method: collectForm.method,
    collector: collectForm.collector,
    collectTime: formatDateTime(collectForm.collectTime),
    result: collectForm.result,
    nextCollectTime: collectForm.nextCollectTime ? formatDateTime(collectForm.nextCollectTime) : undefined,
    remark: collectForm.remark
  }
  
  overdueApi.collectRegister(data).then(res => {
    ElMessage.success('催收登记成功')
    collectDialogVisible.value = false
    getTableData()
  }).catch(() => {
    loading.value = false
  })
}

// 还款
const handleRepay = (row) => {
  repayForm.overdueId = row.overdueId
  repayForm.loanNo = row.loanNo
  repayForm.customerName = row.customerName
  repayForm.dueDate = row.dueDate
  repayForm.dueAmount = row.dueAmount
  repayForm.overdueDays = row.overdueDays
  repayForm.penalty = row.penalty
  repayForm.totalAmount = row.totalAmount
  repayForm.payDate = new Date()
  repayForm.payAmount = row.totalAmount
  repayForm.principal = row.principal
  repayForm.interest = row.interest
  repayForm.payMethod = '1' // 默认银行转账
  repayForm.transactionNo = ''
  repayForm.remark = '逾期还款'
  
  repayDialogVisible.value = true
}

// 提交还款
const submitRepay = () => {
  if (!repayForm.payDate || !repayForm.payAmount || !repayForm.payMethod) {
    ElMessage.warning('请填写完整的还款信息')
    return
  }
  
  loading.value = true
  
  const data = {
    overdueId: repayForm.overdueId,
    payDate: formatDate(repayForm.payDate),
    payAmount: repayForm.payAmount,
    principal: repayForm.principal,
    interest: repayForm.interest,
    penalty: repayForm.penalty,
    payMethod: repayForm.payMethod,
    transactionNo: repayForm.transactionNo,
    remark: repayForm.remark
  }
  
  overdueApi.overdueRepay(data).then(res => {
    ElMessage.success('逾期还款成功')
    repayDialogVisible.value = false
    getTableData()
  }).catch(() => {
    loading.value = false
  })
}

// 查看催收记录
const handleRecord = (row) => {
  loading.value = true
  
  overdueApi.getCollectRecords(row.overdueId).then(res => {
    collectRecords.value = res.data
    recordDialogVisible.value = true
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

// 导出
const handleExport = () => {
  ElMessage.success('导出功能待开发')
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  if (typeof date === 'string') return date
  
  const d = new Date(date)
  const year = d.getFullYear()
  const month = (d.getMonth() + 1).toString().padStart(2, '0')
  const day = d.getDate().toString().padStart(2, '0')
  
  return `${year}-${month}-${day}`
}

// 格式化日期时间
const formatDateTime = (date) => {
  if (!date) return ''
  if (typeof date === 'string') return date
  
  const d = new Date(date)
  const year = d.getFullYear()
  const month = (d.getMonth() + 1).toString().padStart(2, '0')
  const day = d.getDate().toString().padStart(2, '0')
  const hours = d.getHours().toString().padStart(2, '0')
  const minutes = d.getMinutes().toString().padStart(2, '0')
  const seconds = d.getSeconds().toString().padStart(2, '0')
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getTableData()
}

// 获取逾期天数类型
const getOverdueType = (days) => {
  if (days <= 30) return 'warning'
  if (days <= 60) return 'danger'
  if (days <= 90) return 'danger'
  return 'danger'
}

// 获取状态类型
const getStatusType = (status) => {
  const map = {
    'pending': 'info',
    'reminded': 'warning',
    'collected': 'primary',
    'settled': 'success'
  }
  return map[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const map = {
    'pending': '未处理',
    'reminded': '已提醒',
    'collected': '已催收',
    'settled': '已结清'
  }
  return map[status] || '未知'
}

// 获取催收方式文本
const getCollectMethodText = (method) => {
  const map = {
    'phone': '电话催收',
    'visit': '上门催收',
    'legal': '法律催收',
    'outsource': '委外催收'
  }
  return map[method] || '未知'
}

// 获取催收结果文本
const getCollectResultText = (result) => {
  switch (result) {
    case 'promise':
      return '承诺还款'
    case 'refuse':
      return '拒绝还款'
    case 'unreachable':
      return '无法联系'
    case 'partial':
      return '部分还款'
    case 'full':
      return '全部还款'
    default:
      return '未知'
  }
}

// 格式化金额
const formatMoney = (value) => {
  return `¥ ${parseFloat(value).toFixed(2)}`
}

// 双击行查看记录
const handleRowDblClick = (row) => {
  handleRecord(row)
}
</script>

<style scoped>
.overdue-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.info-icon {
  color: #409EFF;
  cursor: help;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style> 